package com.top.application.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSONObject;
import com.top.application.entity.UserTokenEntity;
import com.top.application.service.UserTokenService;
import com.top.application.utils.StringUtils;

@WebFilter(urlPatterns = "/*")
public class InitFilter implements Filter{
	
	 private static Logger log = LoggerFactory.getLogger(InitFilter.class);
	  private WebApplicationContext application;
	  private UserTokenService userTokenService;
	  
	  public void destroy() {}
	  
	  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
	    throws IOException, ServletException
	  {
	    HttpServletRequest request = (HttpServletRequest)req;
	    HttpServletResponse response = (HttpServletResponse)res;
	    response.setHeader("Access-Control-Allow-Origin", "*");
	    response.setHeader("Access-Control-Allow-Headers", "User-Agent,token_id,Cache-Control,"
	    		+ "Content-type,token_id,Server,withCredentials,access_token");
	    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
	    JSONObject resultJson = new JSONObject();
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html; charset=utf-8");
	    String requestUrl = request.getRequestURI().toString();
	    if (requestUrl.indexOf("/api") < 0)
	    {
	      chain.doFilter(request, response);
	      return;
	    }
	    log.debug("请求url: " + requestUrl);
	    
	    String[] url = { "/api/oauth/token", "/api/oauth/confirm_token", "/token/getToken" };
	    for (String index : url) {
	      if (requestUrl.contains(index))
	      {
	        chain.doFilter(request, response);
	        return;
	      }
	    }
	    String access_token = request.getHeader("access_token");
	    String token_id = request.getHeader("token_id");
	    try
	    {
	      if ((StringUtils.isEmpty(access_token)) && (StringUtils.isEmpty(token_id)))
	      {
	        resultJson.put("code", "303");
	        resultJson.put("message", "token参数不能为空");
	        PrintWriter out = response.getWriter();
	        out.write(resultJson.toString());
	        out.flush();
	        out.close();
	        
	        return;
	      }
	      Map<String, Object> param = new HashMap<String, Object>();
	      param.put("access_token", access_token);
	      UserTokenEntity userTokenEntity = this.userTokenService.selectByAccessToken(access_token);
	      if (userTokenEntity == null)
	      {
	        resultJson.put("code", "302");
	        resultJson.put("message", "token参数有误");
	        request.setAttribute("resultJson", resultJson);
	        PrintWriter out = response.getWriter();
	        out.write(resultJson.toString());
	        out.flush();
	        out.close();
	        return;
	      }
	      chain.doFilter(request, response);
	    }
	    catch (Exception e)
	    {
	      resultJson.put("code", "500");
	      resultJson.put("message", "系统异常");
	      PrintWriter out = response.getWriter();
	      out.write(resultJson.toString());
	      out.flush();
	      out.close();
	      e.printStackTrace();
	      log.error("系统异常");
	    }
	  }
	  
	  public void init(FilterConfig filterConfig)
	    throws ServletException
	  {
	    this.application = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
	    this.userTokenService = ((UserTokenService)this.application.getBean("userTokenService"));
	  }

}
